package com.tmans.common.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.springframework.web.multipart.MultipartHttpServletRequest;



public class WebUtil
{

	/**
	 * ��� �Ķ���͸� �ؽø����� ����
	 * 
	 * @param request
	 * @param columns
	 * @return
	 */
	public static HashMap<String, Object> getRequestToHashMap( HttpServletRequest request, List<String> columns ) {

		// ���� ����?�ϴ� �÷��� �Ķ���ͷ� �ѱ�� ����..
		boolean hasColumns = false;
		if( columns != null && columns.size() > 0 )
			hasColumns = true;

		Enumeration<String> enums = request.getParameterNames();

		HashMap<String, Object> model = new HashMap<String, Object>();

		while( enums.hasMoreElements() ) {
			String name = enums.nextElement();

			boolean addToModel = false;
			// �÷��� ���ǵ� ��� ����������(���ǵǾ� �ִ� �Ķ����) model �� �߰�
			if( hasColumns ) {
				// ȿ�������� üũ�� ��� �����ϰ�, �켱 ����
				for( int i = 0; i < columns.size(); i++ ) {
					if( name.equals( columns.get( i ) ) ) {
						addToModel = true;
						break;
					}
				}
			}
			else {
				addToModel = true;
			}

			// �Ķ���͸� �𵨿� �߰�
			if( addToModel ) {
				String[] values = request.getParameterValues( name );

				if( values.length == 1 ) {
					model.put( name, request.getParameter( name ) );
				}
				else {
					model.put( name, values );
				}
			}
		}

		return model;
	}

	/**
	 * 
	 * @param request
	 * @return
	 * @see getRequestToHashMap( HttpServletRequest request, List<String> columns )
	 */
	public static HashMap<String, Object> getRequestToHashMap( HttpServletRequest request ) {
		return getRequestToHashMap( request, null );
	}

	public static String getRequestToQueryString( HttpServletRequest request, List<String> input ) {
		return toQueryString( getRequestToHashMap( request, input ) );
	}
	
	/**
	 * �߰����� �Ķ���͸� ������ ���.<br/>
	 * �������, searchParam ��������� op�� ���ܵ�����, �����Ǿ��� �� �⺻(list)�� �ƴ� �ٸ� op=xxx ���� �߰��ϰ� ���� ���.<br/>
	 * UNDONE : �ߺ��� ��� input2 �� �켱�ϰ� ó���ؾ� ��.
	 * @param request
	 * @param input request �κ��� ����?�� key
	 * @param input2 �߰� �Ķ���� key/value
	 * @return
	 */
	public static String getRequestToQueryString( HttpServletRequest request, List<String> input, HashMap<String, Object> input2) {
		String queryString = toQueryString( getRequestToHashMap( request, input ) );
		String queryString2 = toQueryString( input2 );
		
		if( queryString.length() == 0)
			return queryString2;
		
		if( queryString2.length() > 0) {
			return queryString + "&" + queryString2.substring( 1 );
		}
		
		return queryString;
	}
	
	public static String getRequestToQueryString( HttpServletRequest request, List<String> input, String input2) {
		String queryString = toQueryString( getRequestToHashMap( request, input ) );
		String queryString2 = input2;
		
		if( queryString.length() == 0)
			return "?" + queryString2;
		
		if( queryString2.length() > 0) {
			return queryString + "&" + queryString2;
		}
		
		return queryString;
	}

	/**
	 * ���� ���ڿ�/���� �ƴ� ��� ���� ?A=1234&B=5678 ����� ������Ʈ������ ����<br/>
	 * ��� �ѱ��� ���� �׷��� ���� ����.<br/>
	 * ���콺 ���� ������ EUC-KR�� ���ڵ���.
	 * 
	 * @param input �Ľ��� ��
	 * @return �Ľ̵� ���ڿ�(GET���� ���� QueryString)
	 */
	public static String toQueryString( HashMap<String, Object> input ) {
		String result = "";

		Set<String> set = input.keySet();
		Iterator<String> iter = set.iterator();

		while( iter.hasNext() ) {

			String key = iter.next();
			String value = StringUtil.noNull( input.get( key ) );

			if( !StringUtil.isBlank( value ) ) {
				
				if( result.length() > 0 )
					result += "&";
				
				try {
					String query = key + "=" + URLEncoder.encode( value, "EUC-KR" );
					result += query;
				} catch( Exception ex ) {
				}
			}
		}

		if( result.length() > 0 )
			result = "?" + result;

		return result;

	}

	/**
	 * ��Ʈ�ѷ����� ����, ������ �� ���Ͼ��� �� ������ �̵�. STATIC CONST�� ��Ʈ�������� �ʴ´�. (�򰥸�)
	 * 
	 * @param response
	 * @param message
	 * @param redirectUrl
	 * @throws IOException
	 */
	public static int	JS_CLOSE	= 1;	// _self.close();
	public static int	JS_BACK		= 2;	// history.back();
	public static int	JS_OPENER	= 3;	// opener.location.reload(); _self.close();

	public static void printJsAlert( HttpServletResponse response, String message, String redirectUrl ) {
		try {
			response.setHeader( "Content-Type", "text/html; charset=EUC-KR" );
			PrintWriter out = response.getWriter();
			out.println( "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">" );
			out.println( "<html lang=\"ko\" xmlns=\"http://www.w3.org/1999/xhtml\">" );
			out.println( "<head>" );
			out.println( "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=euc-kr\"/>" );
			out.println( "<title>��������û</title>" );
			out.println( "</head>" );
			out.println( "<body>" );
			
			// -- ���� : SCRIPT -----------------------------------------------
			out.println( "<script type=\"text/javascript\">" );
			out.println( "//<![CDATA[" );
			if( !StringUtil.isBlank(message) ) {
				out.print( "alert(\"" );
				out.print( message.replaceAll( "\n", "\\\\n" ) );
				out.print( "\");\n" );
			}

			if( redirectUrl != null ) {
				if( redirectUrl.equals( "CLOSE" ) )
					out.println( "window.close();" );
				else if( redirectUrl.equals( "BACK" ) )
					out.println( "history.back();" );
				else if( redirectUrl.equals( "OPENER" ) )
					out.println( "opener.location.reload(); window.close();" );
				else
					out.println( "window.location = \"" + redirectUrl + "\";" );
			}
			out.println( "//]]>" );
			out.println( "</script>" );
			// -- ���� : SCRIPT -----------------------------------------------
			
			// -- ���� : NOSCRIPT ---------------------------------------------
			out.println( "<noscript>" );

			if( !StringUtil.isBlank(message) ) {
				out.print( "<p>" );
				out.print( StringUtil.htmlEncode( message, true, false ) );
				out.print( "</p>" );
				out.print( "<br/>" );
			}
			
			if( redirectUrl != null ) {
				if( redirectUrl.equals( "CLOSE" ) )
					out.print( "���� â�� �ݽ��ϴ�." );
				else if( redirectUrl.equals( "BACK" ) )
					out.print( "���� �������� ���ư��ϴ�." );
				else if( redirectUrl.equals( "OPENER" ) )
					out.print( "�θ�â�� ���ΰ�ħ �� �� ���� â�� �ݽ��ϴ�." );
				else
					out.print( "������ �̵� : <a href=\"" + redirectUrl.replaceAll( "&", "&amp;" ) + "\">" + redirectUrl.replaceAll( "&", "&amp;" ) +"</a>" );
			}
			out.println( "</noscript>" );
			// -- ���� : NOSCRIPT ---------------------------------------------
			
			out.println( "</body>" );
			out.println( "</html>" );
			
			out.close();
		} catch( IOException e ) {
		}
	}
	
	public static void printJs( HttpServletResponse response, String jsScript ) {
		try {
			response.setHeader( "Content-Type", "text/html; charset=EUC-KR" );
			PrintWriter out = response.getWriter();
			out.println( "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">" );
			out.println( "<html lang=\"ko\" xmlns=\"http://www.w3.org/1999/xhtml\">" );
			out.println( "<head>" );
			out.println( "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=euc-kr\"/>" );
			out.println( "<title>��������û</title>" );
			out.println( "</head>" );
			out.println( "<body>" );
			out.println( "<script type=\"text/javascript\">" );
			out.println( "//<![CDATA[" );
			
			if( !StringUtil.isBlank( jsScript ) ) {
				out.println( jsScript );
			}
			
			out.println( "//]]>" );
			out.println( "</script>" );
			out.println( "</body>" );
			out.println( "</html>" );
		} 
		catch( IOException e ) {
		}
	}

	public static void printJsAlert( HttpServletResponse response, String message ) {
		printJsAlert( response, message, null );
	}

	public static void printJsAlert( HttpServletResponse response ) {
		printJsAlert( response, null, null );
	}

	public static void printJsAlert( HttpServletResponse response, String message, int type ) {
		String typeName = null;
		if( type == 1 )
			typeName = "CLOSE";
		if( type == 2 )
			typeName = "BACK";
		if( type == 3 )
			typeName = "OPENER";
		printJsAlert( response, message, typeName );
	}

	/**
	 * �ܼ� ��ũ��Ʈ�� �ھƳ��� ���
	 * 
	 * @param response
	 * @param message
	 * @param scriptStr
	 * @throws IOException
	 */
	public static void printJsAlertScript( HttpServletResponse response, String message, String scriptStr ) {
		try {
			response.setHeader( "Content-Type", "text/html; charset=EUC-KR" );
			PrintWriter out = response.getWriter();
			out.println( "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">" );
			out.println( "<html lang=\"ko\" xmlns=\"http://www.w3.org/1999/xhtml\">" );
			out.println( "<head>" );
			out.println( "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=euc-kr\"/>" );
			out.println( "<title>��������û</title>" );
			out.println( "</head>" );
			out.println( "<body>" );
			out.println( "<script type=\"text/javascript\">" );
			out.println( "//<![CDATA[" );

			if( !StringUtil.isBlank( message ) ) {
				out.print( "alert(\"" );
				out.print( message );
				out.print( "\");\n" );
			}

			if( !StringUtil.isBlank( scriptStr ) ) {
				out.println( scriptStr );
			}
			
			out.println( "//]]>" );
			out.println( "</script>" );
			out.println( "</body>" );
			out.println( "</html>" );
			out.close();
		} catch( IOException e ) {
		}
	}

	/**
	 * �ܼ� �޽���ó�� for Ajax
	 * 
	 * @param response
	 * @param message
	 * @throws IOException
	 */
	public static void printJsAjax( HttpServletResponse response, String message ) {
		try {
			response.setHeader( "Content-Type", "text/html; charset=EUC-KR" );
			PrintWriter out = response.getWriter();

			if( !StringUtil.isBlank( message ) ) {
				out.print( message );
			}

			out.close();
		} catch( IOException e ) {
		}
	}

	/**
	 * ���� URL �������� (GET ONLY)
	 * @param request
	 * @return
	 */
	public static String getURL( HttpServletRequest request ) {
		StringBuffer strURL = new StringBuffer();
		/*
		StringBuffer strParam = new StringBuffer();
		Enumeration<?> param = request.getParameterNames();
		
		if( param.hasMoreElements() ) {
			strParam.append( "?" );
		}
		while( param.hasMoreElements() ) {
			String name = (String) param.nextElement();
			String value = request.getParameter( name );
			strParam.append( name + "=" + value );
			if( param.hasMoreElements() ) {
				strParam.append( "&" );
			}
		}
		*/
		
		//strURL.append( strParam );
		
		String uri = request.getRequestURI();
		String queryString = request.getQueryString();
		
		strURL.append( uri );
		if( !StringUtil.isBlank( queryString ) ) {
			strURL.append( "?" );
			strURL.append( queryString );
		}
		return strURL.toString();
	}
	
	/**
	 * AJAX ���� �Ķ���� �ѱ۷� �ѱ涧 UTF-8�� �ޱ�
	 * @param String
	 * @param String
	 * @return String
	 */
	public static String setAjaxCharSet(String value, String charSet){
		String temp = null;
		try {
			temp =  URLDecoder.decode(value, charSet);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return temp;
	}
	
	/**
	 * ���� URL �ΰ�?
	 * @param request
	 * @return
	 */
	public static boolean isAdminUrl( HttpServletRequest request ){

		// VIEW������ ����ϱ� ���� �켱 ������ �� ���� Ȯ��.
		String requestUri = (String) request.getAttribute("javax.servlet.forward.request_uri");
		if( requestUri == null )
			requestUri = request.getRequestURI();
		
		if( requestUri.startsWith( "/hcms/" ))
			return true;
		
		return false;
	}

	/**
	 * �信�� ���� ÷������ ���� �������� ��� ���� ���
	 * @param fileNm ���ϸ�
	 * @return <img src="/images/common/file/___.gif"/>
	 */
	public static String getFileIcon( Object fileNm ) {
		
		String fileIcoS = "<img src=\"/images/common/file/";
		String fileIcoE = ".gif\" width=\"16\" height=\"16\" alt=\"" + StringUtil.noNull( fileNm ) + "\"/>";
		String fileIco = "default";
		
		String fileExt = StringUtil.noNull( fileNm );
		fileExt = fileExt.substring( fileExt.lastIndexOf( "." ) + 1 ).toLowerCase();
		
		if( fileExt.equals( "hwp" ) ) {
			fileIco = "hwp";
		}
		else if( fileExt.equals( "pdf" ) ) {
			fileIco = "pdf";	
		}
		else if( fileExt.equals( "xls" ) ) {
			fileIco = "xls";		
		}
		else if( fileExt.equals( "ppt" ) ) {
			fileIco = "ppt";
		}
		else if( fileExt.equals( "zip" ) || fileExt.equals( "rar" ) || fileExt.equals( "alz" ) || fileExt.equals( "a00" ) ) {
			fileIco = "zip";
		}
		else if( fileExt.equals( "txt" ) ) {
			fileIco = "txt";
		}
		else if( fileExt.equals( "jpg" ) || fileExt.equals( "png" ) || fileExt.equals( "bmp" ) || fileExt.equals( "gif" ) ) {
			fileIco = "jpg";
		}
		else if( fileExt.equals( "htm" ) || fileExt.equals( "html" ) ) {
			fileIco = "html";
		}
		else if( fileExt.equals( "exe" ) || fileExt.equals( "com" ) ) {
			fileIco = "exe";
		}
		
		return fileIcoS + fileIco + fileIcoE;
	}
	
	
	
}

